package com.app.controller;

import com.app.enums.StatusCodeEnum;
import com.app.model.JiuquanUserModel;
import com.app.model.PushModel;
import com.app.service.PushService;
import com.app.service.UserService;
import com.app.util.Result;
import com.app.util.TokenUtils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;

//弹窗推送
@RestController
@Controller
@RequestMapping("/jiuquan/push")
public class PushController {
    @Autowired
    private PushService pushService;
    @Autowired
    private UserService userService;

    //查询是否已推送
    @GetMapping("/getPushInfo")
    public Result getPushInfo(HttpServletRequest request) {
        String token = request.getHeader("token");
        if (token == null) {
            return Result.error(StatusCodeEnum.STATUS405.getCode(), StatusCodeEnum.STATUS405.getMsg());
        }
        String openId = TokenUtils.verify(token);
        JiuquanUserModel userInfo = userService.getUserByOpenid(openId);
        if (userInfo == null) {
            return Result.error(StatusCodeEnum.STATUS406.getCode(), StatusCodeEnum.STATUS406.getMsg());
        }
        QueryWrapper<PushModel> qw = new QueryWrapper<>();
        qw.eq("user_id", userInfo.getId());
        PushModel push = pushService.getOne(qw);
        if (push == null) {
            PushModel pushModel = new PushModel();
            pushModel.setUserId(userInfo.getId());
            pushService.save(pushModel);
        }
        PushModel pushModel = pushService.getOne(qw);
        return Result.success(pushModel);
    }

    //确认已推送
    @PostMapping("/updatePopup")
    public Result updatePopup(HttpServletRequest request) {
        String token = request.getHeader("token");
        if (token == null) {
            return Result.error(StatusCodeEnum.STATUS405.getCode(), StatusCodeEnum.STATUS405.getMsg());
        }
        String openId = TokenUtils.verify(token);
        PushModel pushModel = new PushModel();
        pushModel.setPopupStatus(1);
        pushModel.setPushMessage(1);

        JiuquanUserModel userInfo = userService.getUserByOpenid(openId);
        UpdateWrapper<PushModel> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("user_id", userInfo.getId());
        pushService.update(pushModel, updateWrapper);
        return Result.success("修改成功");
    }

    //清空整张表数据
    @GetMapping("/delAllPopup")
    public Result delAllPopup() {
        pushService.remove(null);
        return Result.success("删除所有数据成功");
    }
}
